const mongoose = require('mongoose');
const dbConfig = require('../config/db');

// 连接MongoDB数据库
const connectDB = async () => {
  try {
    const conn = await mongoose.connect(dbConfig.url, dbConfig.options);
    console.log(`MongoDB Connected: ${conn.connection.host}`);

    // 监听连接错误事件
    mongoose.connection.on('error', (err) => {
      console.error('MongoDB connection error:', err);
      setTimeout(connectDB, 5000); // 5秒后重试连接
    });

    // 监听断开连接事件
    mongoose.connection.on('disconnected', () => {
      console.log('MongoDB disconnected, trying to reconnect...');
      setTimeout(connectDB, 5000);
    });

    // 监听进程终止事件，确保关闭数据库连接
    process.on('SIGINT', async () => {
      await mongoose.connection.close();
      console.log('MongoDB connection closed through app termination');
      process.exit(0);
    });

  } catch (error) {
    console.error('Error connecting to MongoDB:', error.message);
    process.exit(1);
  }
};

module.exports = connectDB;